package com.bitter.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author thomas.he
 * @date 2022/6/95
 * 1 、有可重入锁
 * 2、公平锁
 * 3、闭锁
 * 4、信号量
 * 6、读写锁
 **/
@RestController
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping(value = "/redisson/{key}")
    public String redissonTest(@PathVariable("key") String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        System.out.println("lock--->" + lock);
        try {
            lock.lock();
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //判断是否还是锁定状态 ----延迟时间
            if (lock.isLocked()) {
                // 是当前执行线程的锁
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock(); //释放锁
                }
            }
        }
        return "已解锁" + System.currentTimeMillis();
    }

    @RequestMapping("/redisson/getlock")
    public String testRedisson() {
        //获取分布式锁，只要锁的名字⼀样，就是同⼀把锁

        RLock lock = redissonClient.getLock("lock");
        //加锁（阻塞等待），默认过期时间是30秒
        lock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("加锁成功，执⾏业务逻辑");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁，如果业务执⾏完成，就不会继续续期，即使没有⼿动释放锁，在30秒过后，也会释放锁
            lock.unlock();
        }
        return "Hello redission";
    }
}
